package com.gugee.ins.data.analysis.service.impl;

import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.ins.common.constant.AiConst;
import com.gugee.ins.common.dal.ai.AiAnalysisClient;
import com.gugee.ins.common.dal.service.product.InsProductDao;
import com.gugee.ins.common.model.ai.*;
import com.gugee.ins.data.analysis.config.InsAnalysisConfig;
import com.gugee.ins.data.analysis.service.InsAnalysisProductCategoryService;
import com.gugee.ins.data.common.msg.InsProductMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * insBloggerLocation 服务
 * @author Huangxin
 */
@Slf4j
@Service
public class InsAnalysisProductCategoryServiceImpl implements InsAnalysisProductCategoryService {

    /**
     * 配置
     */
    @Autowired
    InsAnalysisConfig insAnalysisConfig;

    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    /**
     * ai
     */
    @Autowired
    AiAnalysisClient aiAnalysisClient;

    /**
     * insProductDao
     */
    @Autowired
    InsProductDao insProductDao;

    /**
     * 线程池
     */
    ForkJoinPool forkJoinPool;



    /**
     * 线程名
     */
    private String workName = "insProductCategory";

    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        forkJoinPool = ThreadPoolUtils.forkJoinPool(insAnalysisConfig.getInsAnalysisProductCategoryCorePollSize(), workName);
        scheduleTemplate.attach(workName, forkJoinPool);
    }

    /**
     * 处理 分析播主分类 任务
     * @param insProductMessages
     */
    @Override
    public void handle(List<InsProductMessage> insProductMessages) {
        try {
            if(!insProductMessages.isEmpty()){
                forkJoinPool.submit(() -> insProductMessages.parallelStream().forEach(insProductMessage -> {
                    try {
                        // 分析
                        analysisCategory(insProductMessage);
                    } catch (Exception ex) {
                        log.error("insAnalysisProductCategory error. pid:{}, error :{}" ,
                                insProductMessage.getPid(),ex.getMessage());
                    }
                })).get();
            }
        } catch (Exception ex) {
            log.error("insAnalysisProductCategory thread error.  {}" ,  ex.getMessage());
        }
    }

    /**
     * 分析
     *
     * @param insProductMessage
     */
    public void analysisCategory(InsProductMessage insProductMessage){
        long start = System.currentTimeMillis();
        // 封装数据
        InsProductCategoryRequest insProductCategoryRequest = new InsProductCategoryRequest();
        insProductCategoryRequest.setTitle(insProductMessage.getProductName());
        insProductCategoryRequest.setDesc(insProductMessage.getDescription());
        insProductCategoryRequest.setLinkurl(insProductMessage.getExternalUrl());
        try{
            String cate = "";
            // 调用接口
            InsProductCategoryResponse insProductCategoryResponse = aiAnalysisClient.getProductCategory(insProductCategoryRequest);
            if(insProductCategoryResponse != null && !AiConst.PRODUCT_CATE_UNKNOWN.equals(insProductCategoryResponse.getCate())){
                cate = insProductCategoryResponse.getCate();
            }

            // 更新
            insProductDao.updateCate(insProductMessage.getPid(),cate);
        }catch (Exception e){
            log.error("insAnalysisProductCategory get ai result error ,msg:{}",e.getMessage());
        }

        if ((System.currentTimeMillis() - start) / 1000 > insAnalysisConfig.getInsAnalysisDebugTimeLimit()) {
            log.info("insAnalysisProductCategory pid:{} use time:{}s", insProductMessage.getPid(),(System.currentTimeMillis() - start) / 1000);
        }
    }
}
